package com.hluobo.gnnulibrary.ui;

import java.util.ArrayList;
import java.util.List;

import com.hluobo.gnnulibrary.R;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

	private static final String TAG = "com.hluobo.gnnulibrary";
	private static final String MY_PREFERENCES = "preferences";
	
	private static final String TAG_HOME = "com.hluobo.gnnulibrary.home";
	private static final String TAG_SEARCH = "com.hluobo.gnnulibrary.search";
	private static final String TAG_ACCOUNT = "com.hluobo.gnnulibrary.account";
	private static final String TAG_MORE = "com.hluobo.gnnulibrary.more";

	private ImageView iv_home;
	private ImageView iv_search;
	private ImageView iv_account;
	private ImageView iv_more;
	private ImageView iv_navigation_shadow;
	
	private TextView tv_titlebar;

	private List<Fragment> fragments = new ArrayList<Fragment>();
	private SharedPreferences preferences;

	private static int lastActiveTab = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		preferences = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
		
		tv_titlebar = (TextView) findViewById(R.id.titlebar);

		initNavigation();
		
		selectTab(TAG_HOME);

	}

	@Override
	public void onAttachFragment(Fragment fragment) {
		// TODO Auto-generated method stub
		super.onAttachFragment(fragment);
		Log.i(TAG, "MainActivity onAttachFragment");
	}



	private void selectTab(String tag) {
		Fragment f = this.getFragmentManager().findFragmentByTag(tag);
		FragmentTransaction ft = this.getFragmentManager()
				.beginTransaction();
		if(null == f){
			f = Fragment.instantiate(this, HomeFragment.class.getName(),
					null);
			ft.add(R.id.main_container, f, tag);
			Log.i(TAG, "第一次"+tag);
		}else if(f.isDetached()){
			ft.attach(f);
		}
		ft.commit();
		fragments.add(f);
	}

	private void initNavigation() {

		iv_home = (ImageView) findViewById(R.id.navigation_iv_home);
		iv_search = (ImageView) findViewById(R.id.navigation_iv_search);
		iv_account = (ImageView) findViewById(R.id.navigation_iv_account);
		iv_more = (ImageView) findViewById(R.id.navigation_iv_more);

		iv_home.setOnClickListener(new NavigationClickListener<HomeFragment>(
				this, TAG_HOME, HomeFragment.class));

		iv_search
				.setOnClickListener(new NavigationClickListener<SearchFragment>(
						this, TAG_SEARCH, SearchFragment.class));
		iv_account
				.setOnClickListener(new NavigationClickListener<AccountScrenn.AccountFragment>(
						this, TAG_ACCOUNT, AccountScrenn.AccountFragment.class));
		iv_more.setOnClickListener(new NavigationClickListener<MoreScrenn.ExtraFragment>(
				this, TAG_MORE, MoreScrenn.ExtraFragment.class));

		iv_navigation_shadow = (ImageView) findViewById(R.id.navigation_selected_shadow);

	}

	class NavigationClickListener<T extends Fragment> implements
			View.OnClickListener {

		private final Activity mActivity;
		private final String mTag;
		private final Class<T> mClass;
		private final Bundle mArgs;

		private Fragment mFragment;

		public NavigationClickListener(Activity activity, String tag,
				Class<T> clz) {
			this(activity, tag, clz, null);
		}

		public NavigationClickListener(Activity activity, String tag,
				Class<T> clz, Bundle args) {
			mActivity = activity;
			mTag = tag;
			mClass = clz;
			mArgs = args;
		}

		@Override
		public void onClick(View v) {

			FragmentTransaction ft = mActivity.getFragmentManager()
					.beginTransaction();

			// 去掉前面的Fragment
			detachPreviousFragment(ft);
			
			mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
			
			if (mFragment == null) {
				
				boolean rememberMe = preferences.getBoolean("rememberMe", false);
				if(mTag.equals(TAG_ACCOUNT) && !rememberMe){
					// 登陆界面
					mFragment = Fragment.instantiate(mActivity, LoginFragment.class.getName(),
							mArgs);
					Log.i(TAG, "未登录，进入登陆界面！");
				}else{
					mFragment = Fragment.instantiate(mActivity, mClass.getName(),
							mArgs);
				}
				ft.add(R.id.main_container, mFragment, mTag);
				Log.i(TAG, "第二次"+mTag);
			} else if(mFragment.isDetached()) {
				ft.attach(mFragment);
			}
			
			ft.commit();
			fragments.add(mFragment);
			
			Log.i(TAG, "进入导航 -> "+mTag);
			
			// 开始动画
			startNavigationAnimator(v);

		}

		private void changeTitlebarText(String tag) {
			
			if(tag.equals(TAG_HOME)){
				tv_titlebar.setText(R.string.titlebar_home);
			}else if(tag.equals(TAG_SEARCH)){
				tv_titlebar.setText(R.string.titlebar_search);
			}else if(tag.equals(TAG_ACCOUNT)){
				tv_titlebar.setText(R.string.titlebar_account);
			}else if(tag.equals(TAG_MORE)){
				tv_titlebar.setText(R.string.titlebar_more);
			}
			
		}

		/**
		 * 导航条滑动动画
		 * @param v
		 */
		private void startNavigationAnimator(View v) {

			Animation animation = null;
			// TODO 偏移量死地，应该动态获取
			float offset = 180f;

			int which = 0;
			switch (v.getId()) {
			case R.id.navigation_iv_home:
				which = 0;
				break;
			case R.id.navigation_iv_search:
				which = 1;
				break;
			case R.id.navigation_iv_account:
				which = 2;
				break;
			case R.id.navigation_iv_more:
				which = 3;
				break;
			}

			if (which != lastActiveTab) {
				
				// 改变标题
				changeTitlebarText(mTag);

				animation = new TranslateAnimation(lastActiveTab * offset,
						which * offset, 0, 0);

				animation.setFillAfter(true);// True:图片停在动画结束位置
				animation.setDuration(200);
				iv_navigation_shadow.startAnimation(animation);

			}

			lastActiveTab = which;

		}

		/**
		 * 移除前一个Fragment
		 * @param ft
		 */
		private void detachPreviousFragment(FragmentTransaction ft) {
			if (fragments != null && fragments.size() != 0) {
				Log.i(TAG, "fragments size"+fragments.size());
				for (Fragment f : fragments) {
					if (!f.getTag().equals(mTag)) {
						ft.detach(f);
					}
				}
				fragments.clear();
			}
		}

	}

}
